﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace GComp.Apps.EasyStock.DataModel.Common {
    class HistoryQuery : YQLQuery {
        const string QueryTemplate = "select * from yahoo.finance.historicaldata where symbol = \"{0}\" and startDate = \"{1:yyyy-MM-dd}\" and endDate = \"{2:yyyy-MM-dd}\"";

        public HistoryQuery(string symbol, DateTime start, DateTime end) {
            _query = string.Format(QueryTemplate, symbol, start, end);
        }

        public HistoryQuery(string symbol)
            : this(symbol, DateTime.Today.Subtract(TimeSpan.FromDays(30)), DateTime.Today) { }

        public async Task<List<Tuple<DateTime, decimal>>> GetAnswerAsync() {
            try {
                XDocument doc = await GetXmlAnswerAsync();

                Debug.WriteLine("doc: " + doc.ToString());
                
                List<Tuple<DateTime, decimal>> result = new List<Tuple<DateTime, decimal>>();
                foreach (var quote in doc.Descendants("quote")) {
                    DateTime date;
                    string strTmp = quote.Element("Date").Value;
                    DateTime.TryParseExact(strTmp, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
                    decimal value;
                    strTmp = quote.Element("Adj_Close").Value;
                    decimal.TryParse(strTmp, NumberStyles.Any, CultureInfo.InvariantCulture, out value);
                    result.Insert(0, new Tuple<DateTime, decimal>(date, value));
                }
                return result;
            } catch (Exception e) {
                return null;
            }
        }
    }
}
